﻿/* $RCSFile: FullCalloutCampaign.ascx.cs $
 * Copyright (C) Addon Nice Technologies 2010
 * $Source: ?/Addon Nice/AddonNice/AddonNice.LeadProspection/PageModules/CalloutCampaign/FullCalloutCampaign.ascx.cs $
 * $log$
 * Revision 24 2010/08/09 11:16:26  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 11 2010/08/09 10:18:24  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using System.Web.Configuration;
using AddonNice.Configuration.Settings;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.Generic;
using System.Web.Security;
using System.Xml;
using System.Configuration;

using AddonNice;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;

using AddonNice.LeadProspection.Settings;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CalloutCampaign
{

    #region Local TraceSwitch 
	
    public class FullCalloutCampaignTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("FullCalloutCampaignTrace","Special Trace Switch for FullCalloutCampaign");
	}
	#endregion Local TraceSwitch 

    /// <summary>
    /// Initializer class for FullCalloutCampaign 
    /// </summary>
    public class FullCalloutCampaignSI : PortalCRMModuleControlSI
    {
        public FullCalloutCampaignSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FullCalloutCampaignSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FullCalloutCampaignSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FullCalloutCampaignSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                           =   pm.ExtendedResourcesGroup;

            SettingItemSpecial FixedCampaign        =   new SettingItemSpecial(PStr.FixedCampaign,new BooleanDataType());
            FixedCampaign.Required                  =   false;
            FixedCampaign.ResourceFile              =   PStr.ResourceFile;
            FixedCampaign.ResourceItem              =   PStr.ResourceItem;
            FixedCampaign.Value                     =   StStr.strFalse;
            FixedCampaign.Order                     =   40;
            FixedCampaign.ExtendedGroupName         =   extgrp;
            FixedCampaign.EnglishName               =   "Fixed Campaign";
            FixedCampaign.Description               =   "When checked, module will use the campain selected in next setting";
            bSettings.AddSetting(FixedCampaign);

            //Fixed campaign
            WSListDataType defCampaign              =   new WSListDataType(CrmStr.campaign,StStr.smName, "ID");
            SettingItemSpecial Campaign             =   new SettingItemSpecial(PStr.MCampaign,defCampaign);
            Campaign.EnglishName                    =   "Campaign";
            Campaign.Order                          =   50;
            Campaign.ResourceFile                   =   PStr.ResourceFile;
            Campaign.ResourceItem                   =   PStr.ResourceItem;
            Campaign.ExtendedGroupName              =   extgrp;
            Campaign.Description                    =   "Select a default campaign to associate with this Rating";
            Campaign.SettingItemsEvent              +=  new SettingItemsEventHandler(Campaign_SettingItemsEvent);
            bSettings.AddSetting(Campaign);

            SettingItemSpecial CacheDelay        =   new SettingItemSpecial(PStr.CacheDelay,new IntegerDataType());
            CacheDelay.Required                  =   false;
            CacheDelay.ResourceFile              =   PStr.ResourceFile;
            CacheDelay.ResourceItem              =   PStr.ResourceItem;
            CacheDelay.Value                     =   "30";
            CacheDelay.Order                     =   60;
            CacheDelay.ExtendedGroupName         =   extgrp;
            CacheDelay.EnglishName               =   "Cache delay";
            CacheDelay.Description               =   "Delay in minutes for the project items elements";
            bSettings.AddSetting(CacheDelay);

            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]FullCalloutCampaignSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
        
        /// <summary>
        /// Used to set the good display value in Campaign when loaded from DB
        /// </summary>
        void Campaign_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( FullCalloutCampaignTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaignSI Campaign_SettingItemsEvent Guid: {0}", e.Data),FullCalloutCampaignTrace.Sw.Info);
            Guid custId                     =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynCampaign dynac            =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defCampaign      =   (WSListDataType )((SettingItem)sender).DataType;
            defCampaign.DisplayTextValue    =   dynac.name;
            if ( FullCalloutCampaignTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaignSI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),FullCalloutCampaignTrace.Sw.Info);
        }

    }

    public partial class FullCalloutCampaign : PortalCRMModuleControl
    {

		#region Global Implementation

        public override Guid GuidID 
		{
			get
			{
				return new Guid("{1DDACAFE-DE8C-438b-B001-9ABEA71BE5AC}");
			}
		}

		#endregion Global Implementation

        #region Ctor

        
        CalloutCampaignUtil _Util  =   null;
        CalloutCampaignUtil Util
        {
            get
            {
                if ( _Util == null )
                    _Util                           =   new CalloutCampaignUtil(Wrapper,ResetWrapper,(CalloutCampaignID == Guid.Empty) ? dynI.calloutcampaignid:CalloutCampaignID,Settings[PStr.CacheDelay].ToInt());
                return _Util;
            }
        }

        Guid CalloutCampaignID
        {
            get
            {
                object ob                           =   ViewState[PStr.calloutcampaignid];
                if ( ob != null )
                    return (Guid)ob;
                return Guid.Empty;
            }
            set
            {
                ViewState[PStr.calloutcampaignid]   =   value;
            }
        }
       
        ADNDynCalloutCampaign _dynI   =   null;
        ADNDynCalloutCampaign dynI
        {
            get
            {
 			    if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign dynI GET BEG dynI null: {0}, IsUnderCRM: {1}, IsPostBack: {2}",_dynI == null,IsUnderCRM,IsPostBack),FullCalloutCampaignTrace.Sw.Info);
                if ( _dynI != null )
                    return _dynI;
                if ( CalloutCampaignID != Guid.Empty )
                {
                    _dynI                           =   DynEntity.GetFromCache<ADNDynCalloutCampaign>(PStr.calloutcampaign,Wrapper,ResetWrapper,CalloutCampaignID);
		            if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign dynI GET _dynI.Retrieved: {0}",_dynI.Retrieved),FullCalloutCampaignTrace.Sw.Info);
                }
                return _dynI;
            }
        }

        /// <summary>
		/// Ctor Set the properties of the module
		/// </summary>
        public FullCalloutCampaign()
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose || FullCalloutCampaignTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign Ctor enter at: {0}", DateTime.UtcNow), (ModuleTraceSwitch.Sw.TraceVerbose ) ? ModuleTraceSwitch.Sw.Info :FullCalloutCampaignTrace.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
       			const string extgrp                     =   "FULLCALLINGCAMPAIGN";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new FullCalloutCampaignSI(bSettings,this);
        }

        #endregion Ctor

        protected void Page_Load(object sender, EventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose || FullCalloutCampaignTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign Page_Load BEG IsPostBack: {0}, IsInEntityCreationMode : {1}",IsPostBack,IsInEntityCreationMode), (ModuleTraceSwitch.Sw.TraceVerbose ) ? ModuleTraceSwitch.Sw.Info :FullCalloutCampaignTrace.Sw.Info);
            if ( ! IsPostBack )
            {
                // Fill the various PickList combo
                CbCallingProfile.DataTextField              =   StStr.smName;
                CbCallingProfile.DataValueField             =   StStr.smVal;
                CbCallingProfile.DataSource                 =   Wrapper.Util.ListFromPickList(PStr.callingprofile,PStr.calloutcampaign);
                CbCallingProfile.DataBind();

                // Fill the campaign combo
                Guid CampaignId                             =    Settings[PStr.MCampaign].ToGuid();
                if ( FullCalloutCampaignTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaignTrace Page_Load  CampaignId: {0}.",CampaignId),FullCalloutCampaignTrace.Sw.Info);
                // When attached to Crm Form, we extract the CalloutCampaignid from the corresponding entity
                if ( (dynI != null ) && dynI.Retrieved )
                {
                    TbSubject.Text                          =   dynI.subject;
                    RadComboBoxItem it                      =   CbCallingProfile.Items.FindItemByValue(dynI.callingprofile.ToString());
                    if ( it != null )
                        it.Selected                         =   true;
                    TbCallerComment.Text                    =   dynI.comments;
                    if ( dynI.accountid != Guid.Empty )
                    {
                        ADNDynAccount dynC                  =   DynEntity.GetFromCache<ADNDynAccount>(CrmStr.account,Wrapper,ResetWrapper,dynI.accountid);
                        if ( dynC.Retrieved )
                        {
                            RadComboBoxItem itc             =    new RadComboBoxItem(dynC.name,dynC.accountid.ToString());
                            itc.Selected                    =   true;
                            CbAccount.Items.Add(itc);
                            CbAccount.DataBind();
                            if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaignTrace Page_Load Account: {0}.",dynC.name),FullCalloutCampaignTrace.Sw.Info);
                        }
                    }
                    CampaignId                              =   dynI.campaignid;
                }
                 if ( CampaignId != Guid.Empty )
                {
                    ADNDynCampaign dnc                      =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,ResetWrapper,CampaignId);
                    if ( dnc != null )
                    {
                        RadComboBoxItem itc                 =    new RadComboBoxItem(dnc.name,CampaignId.ToString());
                        itc.Selected                        =   true;
                        CbCampaign.Items.Add(itc);
                        CbCampaign.DataBind();
                        if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaignTrace Page_Load Campaign: {0}.",dnc.name),FullCalloutCampaignTrace.Sw.Info);
                    }
                }

                if ( Settings[PStr.FixedCampaign].ToBool() )
                    CbCampaign.Enabled                      =   false;
               EditTable.DataBind();
            }
        }


        void EditTable_NeedDataSource(object sender,SettingsTableEventArgs e)
        {
			if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign EditTable_NeedDataSource BEG Util.EntityID: {0}",Util.EntityID),FullCalloutCampaignTrace.Sw.Info);
            if ( Util.EntityID == Guid.Empty )
            {
			    if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign EditTable_NeedDataSource CalloutCampaignID: {0}",CalloutCampaignID),FullCalloutCampaignTrace.Sw.Info);
                if ( ( CalloutCampaignID != Guid.Empty ) || dynI != null )
                    Util.EntityID   =   CalloutCampaignID;
			    if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign EditTable_NeedDataSource dynI != null: {0}",dynI != null),FullCalloutCampaignTrace.Sw.Info);
            }
            if (  Util.EntityID != Guid.Empty )
                e.CurrentTable.DataSource         =   Util.cSettings;
			if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]FullCalloutCampaign EditTable_NeedDataSource END.",FullCalloutCampaignTrace.Sw.Info);
        }

        void  FullCallingCampaign_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            // Only Update if Input Data is Valid
            if ( FullCalloutCampaignTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign FullCallingCampaign_ADNUpdateModule BEG ModuleID: {0}", ModuleID),FullCalloutCampaignTrace.Sw.Info);
            bool shouldCreate                   =   false;
            if ( dynI == null ) 
            {
                shouldCreate                    =   true;
                _dynI                           =   new ADNDynCalloutCampaign(Wrapper,TbSubject.Text.Trim());
            }
            try
            {
                dynI.callingprofile             =   int.Parse(CbCallingProfile.SelectedValue);
                dynI.comments                   =   TbCallerComment.Text.Trim();
                if ( CbAccount.SelectedValue != null )
                    dynI.accountid              =   new Guid(CbAccount.SelectedValue);
                Guid CampaignId                 =    Settings[PStr.MCampaign].ToGuid();
                if ( Settings[PStr.FixedCampaign].ToBool() )
                {
                    if ( ( CampaignId != Guid.Empty ) && ( dynI.campaignid == Guid.Empty ) )
                        dynI.campaignid         =   CampaignId;
                }
                else
                {
                    if ( CbCampaign.SelectedValue != null )
                        CampaignId              =   new Guid(CbCampaign.SelectedValue);
                }
                if ( shouldCreate )
                    CalloutCampaignID           =   dynI.Create();
                else dynI.Update();
            }
            catch(Exception ex)
            {
                if ( FullCalloutCampaignTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]FullCalloutCampaign FullCallingCampaign_ADNUpdateModule ex: {0}", ex),FullCalloutCampaignTrace.Sw.Info);
                throw;
            }
            try
            {
                // Update settings in the database
                EditTable.UpdateControls();
            }
            catch(Exception ex)
            {
                if ( FullCalloutCampaignTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]FullCalloutCampaign FullCallingCampaign_ADNUpdateModule Editatble.UpdateControls ex: {0}", ex),FullCalloutCampaignTrace.Sw.Info);
                throw;
            }
            if ( FullCalloutCampaignTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign FullCallingCampaign_ADNUpdateModule END ModuleID: {0}", ModuleID),FullCalloutCampaignTrace.Sw.Info);
        }

        void EditTable_UpdateControl(object sender,SettingsTableItemEventArgs e)
        {
			if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign EditTable_UpdateControl BEG TableType: {0}",e.SettingType),FullCalloutCampaignTrace.Sw.Info);
            string key                          =   e.CurrentItem.EnglishName; // beware don't take editcontrol ID because it is upper case
            string val                          =   e.CurrentItem.Value;
            
            ADNDynCallingCampaignItemValue piv  =   null;
            if ( Util.PValuesList.ContainsKey(key) )
            {
			    if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign EditTable_UpdateControl piv found key: {0}",key),FullCalloutCampaignTrace.Sw.Info);
                piv                             =   Util.PValuesList[key];
                piv.value                       =   val;
                piv.Update();
			    if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign EditTable_UpdateControl piv updated val: {0}",val),FullCalloutCampaignTrace.Sw.Info);
            }
            else
            {
			    if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign EditTable_UpdateControl creating piv for key: {0}",key),FullCalloutCampaignTrace.Sw.Info);
                piv                             =   new ADNDynCallingCampaignItemValue(Wrapper,key);
                // get the project item with same key
                ADNDynCallingCampaignItem pi    =   Util.PItemLst[key];
                piv.itemid                      =   pi.callingcampaignitemid;
                piv.value                       =   val;
                piv.calloutcampaignid           =   Util.EntityID;
                piv.Create();
			    if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign EditTable_UpdateControl piv created val: {0}",val),FullCalloutCampaignTrace.Sw.Info);
            }
			if (FullCalloutCampaignTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FullCalloutCampaign EditTable_UpdateControl END key: {0}",key),FullCalloutCampaignTrace.Sw.Info);
        }

        #region Std overrides 

        /// <summary>
        /// Triggered from Page.OnPreInit
        /// We must set the Add button before buttons are initialized by base method
        public override void Page_PreInit(object sender, EventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose || FullCalloutCampaignTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]FullCalloutCampaign Page_PreInit BEG.",(ModuleTraceSwitch.Sw.TraceVerbose ) ? ModuleTraceSwitch.Sw.Info :FullCalloutCampaignTrace.Sw.Info);
            base.Page_PreInit(sender, e);
            string strcult                  =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            updateBtn.SkinID                =   "Update_"+strcult;
            EditTable.NeedDataSource        +=  new SettingsTableEventHandler(EditTable_NeedDataSource);
 			if (ModuleTraceSwitch.Sw.TraceVerbose || FullCalloutCampaignTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]FullCalloutCampaign Page_PreInit END.",(ModuleTraceSwitch.Sw.TraceVerbose ) ? ModuleTraceSwitch.Sw.Info :FullCalloutCampaignTrace.Sw.Info);
       }

		override protected void OnInit(EventArgs e)
		{
			if (ModuleTraceSwitch.Sw.TraceVerbose || FullCalloutCampaignTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]FullCalloutCampaign OnInit BEG.",(ModuleTraceSwitch.Sw.TraceVerbose ) ? ModuleTraceSwitch.Sw.Info :FullCalloutCampaignTrace.Sw.Info);
			InitializeComponent();
			base.OnInit(e);
			if (ModuleTraceSwitch.Sw.TraceVerbose || FullCalloutCampaignTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]FullCalloutCampaign OnInit END.",(ModuleTraceSwitch.Sw.TraceVerbose ) ? ModuleTraceSwitch.Sw.Info :FullCalloutCampaignTrace.Sw.Info);
		}

		private void InitializeComponent()
		{
            Load                            +=  new EventHandler(Page_Load);
            EditTable.UpdateControl         +=  new UpdateControlEventHandler(EditTable_UpdateControl);
            ADNUpdateModule                 +=  new PortalModuleEventHandler(FullCallingCampaign_ADNUpdateModule);
 		}


        #endregion
    }
}